package com.edgclub.edg.activity;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.api.RechargeApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.param.RechargeParam;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.UserPrefUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by LFY on 2016/register_1/14.
 */
public class GzPaymentResult extends GzBaseTooolBarActivity implements View.OnClickListener,VolleyListener{
    // Content View Elements

    private ImageView mZhifutupian;
    private TextView mZhifuzhuangtai;
    private TextView mZhifutishi;
    private Button mBack_zhifu;
    private boolean isQuery = false;
    private UserPrefUtils userPrefUtils;

    private RechargeApi rechargeApi;
    private String buyOrderCode;
    private static Thread mThread = null;
    private int typeNum=0;
    private Animation anim;
    private String money="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment_result);
        bindViews();
        startTimer();
    }

    @Override
    public int getContentView() {
        return R.layout.activity_payment_result;

    }

    @Override
    public void setTitleBarView() {

    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    private void bindViews() {
        userPrefUtils = new UserPrefUtils(this);
        rechargeApi = new RechargeApi(this);
        mZhifutupian = (ImageView) findViewById(R.id.circularButton1);
        mZhifuzhuangtai = (TextView) findViewById(R.id.zhifuzhuangtai);
        mZhifutishi = (TextView) findViewById(R.id.zhifutishi);
        mBack_zhifu = (Button) findViewById(R.id.back_zhifu);
        mBack_zhifu.setOnClickListener(this);
        buyOrderCode=getIntent().getStringExtra("buyOrderCode")+"";
        money=getIntent().getStringExtra("money")+"";
        anim = AnimationUtils.loadAnimation(this, R.anim.my_anim);
        LinearInterpolator lir = new LinearInterpolator();
        anim.setInterpolator(lir);
        setstate(0);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.back_zhifu:
//                Intent intent=new Intent(GzPaymentResult.this,GzRedRechargeActivity.class);
//                intent.putExtra("money",money);
//                startActivity(intent);
                finish();
                break;
        }
    }
    private void setstate(int type){
        switch (type){
            case 0:
                mThread = new Thread(runnableSecondReader);
                mThread.start();
                mZhifuzhuangtai.setText(Html.fromHtml("正在获取支付结果<font color=\"#f02020\">" + mTempTime + "</font>秒<br> 支付成功后自动跳转"));
                mZhifutupian.setBackgroundResource(R.drawable.loading_pay);
                mZhifutupian.startAnimation(anim);
                break;
            case 1:
                mZhifuzhuangtai.setText("支付成功,即将自动跳转");
                anim.cancel();
                mZhifutupian.clearAnimation();
                mZhifutupian.setBackgroundResource(R.drawable.pay_ok);
                handler.sendEmptyMessageDelayed(3,2000);
                break;
            case 2:
                mZhifuzhuangtai.setText("支付失败");
                mZhifutupian.clearAnimation();
                mZhifutupian.setBackgroundResource(R.drawable.pay_erro);
                mZhifutishi.setVisibility(View.VISIBLE);
                mBack_zhifu.setVisibility(View.VISIBLE);
                break;
        }
    }

    boolean isTimeOut;
    int mTempTime=10;
    private  Runnable runnableSecondReader = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while(!isTimeOut){
                if(mTempTime>0){
                    Log.i("TimeOutManager", ""+mTempTime);
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mTempTime--;
                    handler.sendEmptyMessage(1);
                }else if(mTempTime==0){
                    isTimeOut = true;
                    handler.sendEmptyMessage(2);
                }
            }

        }
    };
    private int count = 0;


    private void queryOrder() {
        Log.i("test", "queryOrder + into");
        if (isQuery) {
            return;
        }
        RechargeParam rechargeParam = new RechargeParam();
        rechargeParam.setBuyOrderCode(buyOrderCode);
        rechargeApi.queryOrder(rechargeParam, this);
    }

    @Override
    public void onStart(String tag) {
        isQuery = true;
//            showDialog("正在获取付费", true);
    }

    @Override
    public void onSuccess(String response, String tag) {
        isQuery = false;
        if (JSONHelper.isSuccess(response)) {
            Log.i("test", "queryOrder + success");
            dismissDialog();
            stopTimer();
            count = 0;
            isQuery = false;
            typeNum=1;
            isTimeOut = true;
            handler.sendEmptyMessageDelayed(2, 1000);
        } else {
            typeNum=2;
        }
    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {
        Log.i("test", "queryOrder + stop");
        dismissDialog();
        isQuery = false;
        stopTimer();
        typeNum=2;
        ResultCode.toastVolleyError(this, volleyError);
    }



    // 计时器
    private Timer timer2;
    private TimerTask timerTask2;

    class CountDownTimerTask2 extends TimerTask {

        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    }
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    count++;
                    if (count == 5){
                        count = 0;
                        isQuery = false;
                        dismissDialog();
                        stopTimer();
                        return;
                    }
                    if (isQuery) {
                        return;
                    } else {
                        queryOrder();
                    }


                    break;
                case 1:
                    mZhifuzhuangtai.setText(Html.fromHtml("正在获取支付结果<font color=\"#f02020\">" + mTempTime + "</font>秒<br> 支付成功后自动跳转"));
                    break;
                case 2:
                    setstate(typeNum);
                    break;
                case 3:
                    setResult(RESULT_OK);
                    finish();
                    break;

                default:
                    break;
            }
            super.handleMessage(msg);
        }

    };

    private void startTimer() {
        if (null == timer2) {
            timer2 = new Timer();
        }

        timerTask2 = new CountDownTimerTask2();
        timer2.schedule(timerTask2, 1000 , 1000);
    }

    private void stopTimer() {
        if (null != timer2) {
            timer2.cancel();
            timer2 = null;
        }
        if (null != timerTask2) {
            timerTask2.cancel();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return false;

    }
}